package com.zzyl.job;

import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.service.AlertDataService;
import com.zzyl.service.AlertRuleService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.DeviceDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class AlertRyleJob {
    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private AlertRuleService aleartRuleService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private AlertDataService alertDataService;

    @Scheduled(cron = "0 * * * * ?")
    public void deviceDataAlertFilter(){
        //查询所有报警规则
        List<AlertRule> alertRules = alertRuleMapper.selectByFunctionId(null, null, null);
        if (ObjectUtil.isEmpty(alertRules)){
            return;
        }
        //查询所有设备上报的数据
        List<Object> values = redisTemplate.opsForHash().values("redisdata");
        if (ObjectUtil.isEmpty(values)){
            return;
        }
        //数据格式标准化处理
        ArrayList<DeviceDataVo> deviceDataVos = new ArrayList<>();
        for (Object value : values) {
            //数据格式标准化处理
            List<DeviceDataVo> deviceDataVo = JSONUtil.toList(value.toString(), DeviceDataVo.class);
            deviceDataVos.addAll(deviceDataVo);
        }
        //数据报警处理器
        deviceDataVos.forEach(d -> alertDataService.alertFilter(d));

    }
}
